<?php

class ReceiptComponent extends CComponent 
{
	/**
	 * Receipt status
	 */
	const RECEIPT_ACTIVED = 1;
	const RECEIPT_ATTACHED = 2;
	const RECEIPT_DELETED = 3;
	/**
	 * Upload receipt to server
	 */
	public function uploadReceipt()
	{
		$allowedExts = array("gif", "jpeg", "jpg", "png");
		$temp = explode(".", $_FILES["file"]["name"]);
		$extension = end($temp);
		$bRet = false;
		$result = array(
			'status' =>'KO'
		);

		if ((($_FILES["file"]["type"] == "image/gif")
		|| ($_FILES["file"]["type"] == "image/jpeg")
		|| ($_FILES["file"]["type"] == "image/jpg")
		|| ($_FILES["file"]["type"] == "image/pjpeg")
		|| ($_FILES["file"]["type"] == "image/x-png")
		|| ($_FILES["file"]["type"] == "image/png"))
		&& ($_FILES["file"]["size"] < Yii::app()->params['receiptUploadSize'])
		&& in_array($extension, $allowedExts))
		{

			if ($_FILES["file"]["error"] <= 0)
			{
				if (!file_exists(Yii::app()->params['receiptUploadDir'].'/' . $_FILES["file"]["name"]))
				{
					$fileName = uniqid().'_'.$_FILES["file"]["name"];
					$date = date("Y/m/d");
					$uploadDirectory = Yii::app()->params['receiptUploadDir'].'/' .$date;
					if (!file_exists($uploadDirectory)) {
						mkdir($uploadDirectory, 0777,true);
					}
					move_uploaded_file($_FILES["file"]["tmp_name"],$uploadDirectory.'/'. $fileName);
					$url = Yii::app()->baseUrl.'/upload/receipts/'.$date.'/'.$fileName;
					$command = Yii::app()->db->createCommand("EXEC stp_InsertNewReceipt :Url, :UserId,:ReceiptId,:CreateAt");
					$command->bindValue(':Url', $url, PDO::PARAM_STR);
					$command->bindValue(':UserId', Yii::app()->user->id, PDO::PARAM_INT);
					$command->bindParam(':ReceiptId', $receiptId, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT, 11);
					$command->bindParam(':CreateAt', $createAt, PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 20);
					$command->execute();
					
					$result['status'] = 'OK';
					$result['receipt_id'] = $receiptId;
					$result['file_name']= $fileName;
					$result['url'] = $url;
					$result['create_at'] = $createAt;
										
				}
			}
		}
		return $result;
	}
	/**
	 * 
	 * Load receipt by for searching
	 */
	public function loadReceipt($bIncludeReport = false)
	{

		$from = isset($_POST['startDate']) ? $_POST['startDate'] : date('Y-m-d G:i:s', PHP_INT_MAX + 1);
		$to = isset($_POST['endDate']) ? $_POST['endDate'].' 23:59:59.999' : date('Y-m-d G:i:s', PHP_INT_MAX);
		$status = isset($_POST['receipt_filter_status']) ? $_POST['receipt_filter_status'] : ReceiptComponent::RECEIPT_ACTIVED;
		$pageSize = Yii::app()->params['receiptMinPageSize'];
		$page = isset($_POST['receipt_page']) ? $_POST['receipt_page']: 1;
		$userId = Yii::app()->user->id;
		$command = Yii::app()->db->createCommand("EXEC stp_GetAllReceiptLimited :From, :To,:Status,:PageSize,:Page, :UserId");
		$command->bindValue(':From', $from, PDO::PARAM_STR);
		$command->bindValue('To', $to, PDO::PARAM_STR);
		$command->bindValue(':Status', $status, PDO::PARAM_STR);
		$command->bindValue(':PageSize', $pageSize, PDO::PARAM_INT);
		$command->bindValue(':Page', $page, PDO::PARAM_INT);
		$command->bindValue(':UserId', $userId, PDO::PARAM_INT);
		$rows = $command->queryAll();
		if(!empty($rows)){
			if($bIncludeReport){
				$commandReport = Yii::app()->db->createCommand("EXEC stp_GetReportsActivedLimited :Limit, :Status, :UserId");
				$limit = Yii::app()->params['reportLimitForExpensePage'];
				$commandReport->bindValue(':Limit', $limit, PDO::PARAM_INT);
				$status = ReportComponent::REPORT_ACTIVED;
				$commandReport->bindValue(':Status', $status, PDO::PARAM_INT);
				$commandReport->bindValue(':UserId', $userId, PDO::PARAM_INT);
				$reports = $commandReport->queryAll();
			}
			$result = array(
				'status' => 'OK',
				'rows' => $rows,
				'page' =>$page,
				'limit' =>$pageSize,
				'totalRows' =>$rows[0]['TotalRows'],
				'reports' => isset($reports)?$reports: array()
			);
		} 
		else {
			$result = array(
				'status' => 'KO',
				'reports' => isset($reports)?$reports: array()
			);
		}
		return $result;
	}
}